#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
导出状态显示组件
在状态栏显示导出进度，点击后显示详细的导出任务列表
"""

import logging
from typing import List, Optional

from PySide6.QtCore import Qt, Signal, QTimer, QSize
from PySide6.QtWidgets import (QWidget, QHBoxLayout, QVBoxLayout, QLabel, 
                              QPushButton, QProgressBar, QDialog, QTableWidget,
                              QTableWidgetItem, QHeaderView, QMessageBox,
                              QMenu, QAbstractItemView, QFrame, QSizePolicy,
                              QDialogButtonBox)
from PySide6.QtGui import QIcon, QFont, QColor, QPalette

from core.export_manager import get_export_manager, ExportTask, ExportStatus


# 初始化日志记录器
logger = logging.getLogger("export_status")


class ExportStatusWidget(QWidget):
    """导出状态显示组件，显示在状态栏中"""
    
    def __init__(self, parent=None):
        """初始化导出状态组件"""
        super().__init__(parent)
        self.export_manager = get_export_manager()
        self.current_task_id = None  # 当前显示的任务ID
        
        # 初始化UI
        self._init_ui()
        
        # 连接信号
        self._connect_signals()
        
        # 更新定时器
        self.update_timer = QTimer()
        self.update_timer.timeout.connect(self._update_display)
        self.update_timer.start(1000)  # 每秒更新一次
        
        # 初始状态
        self._update_display()
        
    def _init_ui(self):
        """初始化UI"""
        layout = QHBoxLayout(self)
        layout.setContentsMargins(5, 2, 5, 2)
        layout.setSpacing(5)
        
        # 导出图标
        self.icon_label = QLabel("📤")
        self.icon_label.setFixedSize(16, 16)
        layout.addWidget(self.icon_label)
        
        # 状态文本
        self.status_label = QLabel("无导出任务")
        self.status_label.setMinimumWidth(100)
        font = QFont()
        font.setPointSize(9)
        self.status_label.setFont(font)
        layout.addWidget(self.status_label)
        
        # 设置样式
        self.setStyleSheet("""
            ExportStatusWidget {
                background-color: transparent;
                border: 1px solid #ddd;
                border-radius: 3px;
                padding: 2px;
            }
            ExportStatusWidget:hover {
                background-color: #f0f0f0;
            }
            QLabel {
                color: #666;
            }
        """)
        
        # 设置鼠标点击事件
        self.mousePressEvent = self._on_mouse_press
        
    def _connect_signals(self):
        """连接信号"""
        self.export_manager.task_added.connect(self._on_task_added)
        self.export_manager.task_updated.connect(self._on_task_updated)
        self.export_manager.task_completed.connect(self._on_task_completed)
        
    def _on_task_added(self, task_id: str):
        """新任务添加处理"""
        # 如果当前没有显示任务，显示新任务
        if self.current_task_id is None:
            self.current_task_id = task_id
        self._update_display()
        
    def _on_task_updated(self, task_id: str):
        """任务更新处理"""
        self._update_display()
        
    def _on_task_completed(self, task_id: str, success: bool, message: str):
        """任务完成处理"""
        # 如果完成的是当前显示的任务，切换到下一个活跃任务
        if task_id == self.current_task_id:
            active_tasks = self.export_manager.get_active_tasks()
            if active_tasks:
                self.current_task_id = active_tasks[0].task_id
            else:
                self.current_task_id = None
        self._update_display()
        
    def _update_display(self):
        """更新显示"""
        active_tasks = self.export_manager.get_active_tasks()
        
        if not active_tasks:
            # 没有活跃任务
            self.status_label.setText("无导出任务")
            self.icon_label.setText("📤")
            self.current_task_id = None
            return
            
        # 如果当前任务ID无效，选择第一个活跃任务
        if (self.current_task_id is None or 
            not any(t.task_id == self.current_task_id for t in active_tasks)):
            self.current_task_id = active_tasks[0].task_id
            
        # 获取当前任务
        current_task = self.export_manager.get_task(self.current_task_id)
        if current_task is None:
            return
            
        # 更新状态文本
        if len(active_tasks) == 1:
            status_text = f"{current_task.status_text}"
        else:
            status_text = f"{current_task.status_text} (+{len(active_tasks)-1})"
            
        self.status_label.setText(status_text)
        
        # 更新图标
        if current_task.status == ExportStatus.RUNNING:
            self.icon_label.setText("⏳")
        elif current_task.status == ExportStatus.PENDING:
            self.icon_label.setText("⏸️")
        else:
            self.icon_label.setText("📤")
            
    def _on_mouse_press(self, event):
        """鼠标点击事件"""
        if event.button() == Qt.LeftButton:
            self._show_details_dialog()
            
    def _show_details_dialog(self):
        """显示详情对话框"""
        dialog = ExportTaskDialog(self)
        dialog.exec_()


class ExportTaskDialog(QDialog):
    """导出任务列表对话框"""
    
    def __init__(self, parent=None):
        """初始化对话框"""
        super().__init__(parent)
        self.export_manager = get_export_manager()
        
        self.setWindowTitle("导出任务列表")
        self.setMinimumSize(800, 500)
        self.setModal(False)  # 非模态对话框
        
        # 初始化UI
        self._init_ui()
        
        # 连接信号
        self._connect_signals()
        
        # 加载数据
        self._load_tasks()
        
        # 更新定时器
        self.update_timer = QTimer()
        self.update_timer.timeout.connect(self._load_tasks)
        self.update_timer.start(2000)  # 每2秒更新一次
        
    def _init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        
        # 标题
        title_label = QLabel("导出任务管理")
        title_font = QFont()
        title_font.setPointSize(14)
        title_font.setBold(True)
        title_label.setFont(title_font)
        layout.addWidget(title_label)
        
        # 任务表格
        self.task_table = QTableWidget()
        self.task_table.setColumnCount(7)
        self.task_table.setHorizontalHeaderLabels([
            "文件名", "格式", "数据量", "状态", "进度", "开始时间", "操作"
        ])
        
        # 设置表格属性
        self.task_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.task_table.setAlternatingRowColors(True)
        self.task_table.horizontalHeader().setStretchLastSection(True)
        self.task_table.verticalHeader().setVisible(False)
        
        # 设置行高以确保内容正常显示
        self.task_table.verticalHeader().setDefaultSectionSize(32)
        
        # 设置列宽
        header = self.task_table.horizontalHeader()
        header.resizeSection(0, 200)  # 文件名
        header.resizeSection(1, 60)   # 格式
        header.resizeSection(2, 100)  # 数据量
        header.resizeSection(3, 80)   # 状态
        header.resizeSection(4, 100)  # 进度
        header.resizeSection(5, 120)  # 开始时间
        header.resizeSection(6, 50)   # 操作 - 图标更小，进一步减少宽度
        
        layout.addWidget(self.task_table)
        
        # 底部按钮 - 使用QDialogButtonBox保持一致性
        button_layout = QHBoxLayout()
        
        # 左侧功能按钮
        self.refresh_button = QPushButton("刷新")
        self.refresh_button.clicked.connect(self._load_tasks)
        button_layout.addWidget(self.refresh_button)
        
        self.clear_completed_button = QPushButton("清理已完成")
        self.clear_completed_button.clicked.connect(self._clear_completed_tasks)
        button_layout.addWidget(self.clear_completed_button)
        
        button_layout.addStretch()
        
        # 使用QDialogButtonBox保持与偏好设置一致的样式
        dialog_button_box = QDialogButtonBox(QDialogButtonBox.Close)
        dialog_button_box.rejected.connect(self.close)
        button_layout.addWidget(dialog_button_box)
        
        layout.addLayout(button_layout)
        
    def _connect_signals(self):
        """连接信号"""
        self.export_manager.task_added.connect(self._load_tasks)
        self.export_manager.task_updated.connect(self._load_tasks)
        self.export_manager.task_completed.connect(self._load_tasks)
        
    def _load_tasks(self):
        """加载任务列表"""
        tasks = self.export_manager.get_recent_tasks(50)  # 获取最近50个任务
        
        self.task_table.setRowCount(len(tasks))
        
        for row, task in enumerate(tasks):
            # 文件名
            file_item = QTableWidgetItem(task.file_name)
            file_item.setToolTip(task.file_path)
            self.task_table.setItem(row, 0, file_item)
            
            # 格式
            format_item = QTableWidgetItem(task.format_type.upper())
            self.task_table.setItem(row, 1, format_item)
            
            # 数据量
            data_item = QTableWidgetItem(task.data_info)
            self.task_table.setItem(row, 2, data_item)
            
            # 状态
            status_item = QTableWidgetItem(task.status_text)
            # 根据状态设置颜色
            if task.status == ExportStatus.COMPLETED:
                status_item.setForeground(QColor("#28a745"))  # 绿色
            elif task.status == ExportStatus.FAILED:
                status_item.setForeground(QColor("#dc3545"))  # 红色
            elif task.status == ExportStatus.RUNNING:
                status_item.setForeground(QColor("#007bff"))  # 蓝色
            elif task.status == ExportStatus.CANCELLED:
                status_item.setForeground(QColor("#6c757d"))  # 灰色
            self.task_table.setItem(row, 3, status_item)
            
            # 进度
            if task.status == ExportStatus.RUNNING:
                progress_widget = QProgressBar()
                progress_widget.setValue(task.progress)
                progress_widget.setFixedHeight(20)
                self.task_table.setCellWidget(row, 4, progress_widget)
            else:
                progress_item = QTableWidgetItem(f"{task.progress}%")
                self.task_table.setItem(row, 4, progress_item)
            
            # 开始时间
            if task.start_time:
                import datetime
                start_time = datetime.datetime.fromtimestamp(task.start_time)
                time_item = QTableWidgetItem(start_time.strftime("%H:%M:%S"))
                time_item.setToolTip(start_time.strftime("%Y-%m-%d %H:%M:%S"))
            else:
                time_item = QTableWidgetItem("-")
            self.task_table.setItem(row, 5, time_item)

            # 操作按钮
            action_widget = QWidget()
            action_layout = QHBoxLayout(action_widget)
            action_layout.setContentsMargins(2, 2, 2, 2)  # 统一边距
            action_layout.setSpacing(8)  # 图标间距

            if task.status in [ExportStatus.PENDING, ExportStatus.RUNNING]:
                cancel_icon = QLabel("❌")  # 使用取消图标
                cancel_icon.setFixedSize(18, 18)  # 图标尺寸
                cancel_icon.setAlignment(Qt.AlignCenter)
                cancel_icon.setToolTip("取消任务")  # 添加提示文本
                # 添加点击事件
                cancel_icon.mousePressEvent = lambda event, tid=task.task_id: self._cancel_task(tid) if event.button() == Qt.LeftButton else None
                action_layout.addWidget(cancel_icon)
            elif task.status == ExportStatus.COMPLETED:
                open_icon = QLabel("📂")  # 使用文件夹图标
                open_icon.setFixedSize(18, 18)  # 图标尺寸
                open_icon.setAlignment(Qt.AlignCenter)
                open_icon.setToolTip("打开文件")  # 添加提示文本
                # 添加点击事件
                open_icon.mousePressEvent = lambda event, path=task.file_path: self._open_file(path) if event.button() == Qt.LeftButton else None
                action_layout.addWidget(open_icon)
            elif task.status == ExportStatus.FAILED:
                retry_icon = QLabel("🔄")  # 使用重试图标
                retry_icon.setFixedSize(18, 18)  # 图标尺寸
                retry_icon.setAlignment(Qt.AlignCenter)
                retry_icon.setToolTip("重试任务")  # 添加提示文本
                # 添加点击事件
                retry_icon.mousePressEvent = lambda event, tid=task.task_id: self._retry_task(tid) if event.button() == Qt.LeftButton else None
                action_layout.addWidget(retry_icon)
            
            action_layout.addStretch()
            self.task_table.setCellWidget(row, 6, action_widget)
            
    def _cancel_task(self, task_id: str):
        """取消任务"""
        success = self.export_manager.cancel_task(task_id)
        if success:
            logger.info(f"取消导出任务: {task_id}")
        else:
            QMessageBox.warning(self, "取消失败", "无法取消该任务")
            
    def _open_file(self, file_path: str):
        """打开文件"""
        import os
        import platform
        
        try:
            if platform.system() == "Windows":
                os.startfile(file_path)
            elif platform.system() == "Darwin":  # macOS
                os.system(f"open '{file_path}'")
            else:  # Linux
                os.system(f"xdg-open '{file_path}'")
        except Exception as e:
            QMessageBox.warning(self, "打开失败", f"无法打开文件: {str(e)}")
            
    def _retry_task(self, task_id: str):
        """重试任务"""
        # 这里可以实现重试逻辑
        QMessageBox.information(self, "重试", "重试功能待实现")
        
    def _clear_completed_tasks(self):
        """清理已完成的任务"""
        reply = QMessageBox.question(
            self, 
            "确认清理", 
            "确定要清理所有已完成的任务吗？",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            # 手动清理已完成的任务
            tasks_to_remove = []
            for task_id, task in self.export_manager.tasks.items():
                if task.status in [ExportStatus.COMPLETED, ExportStatus.FAILED, ExportStatus.CANCELLED]:
                    tasks_to_remove.append(task_id)
            
            for task_id in tasks_to_remove:
                if task_id in self.export_manager.tasks:
                    del self.export_manager.tasks[task_id]
                if task_id in self.export_manager.workers:
                    worker = self.export_manager.workers[task_id]
                    worker.deleteLater()
                    del self.export_manager.workers[task_id]
            
            self._load_tasks()
            QMessageBox.information(self, "清理完成", f"已清理 {len(tasks_to_remove)} 个任务")
            
    def closeEvent(self, event):
        """关闭事件"""
        self.update_timer.stop()
        super().closeEvent(event) 